<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-到货单`"
		width="1300px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		:show-confirm-btn="pageType !== 'detail'"
		:show-cancel-btn="pageType !== 'detail'"
		:show-close-btn="pageType === 'detail'"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail' || ruleForm.auditState === 1" label-width="100px" :show-message="false">
			<div ref="box1">
				<div class="flex-between-center margin-bottom-4">
					<el-tag type="primary" effect="plain">
						<span class="el-icon-tickets item-gap"></span>
						<span>基本信息</span>
					</el-tag>
					<div class="flex-end-center">
					</div>
				</div>
				<jk-card class="margin-bottom-10">
					<el-row>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="合同号">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.contract }}</span>
								<el-input v-else v-model="ruleForm.contract" placeholder="合同号" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="存货编码">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.productCode }}</span>
								<remote-search-variety-input
									v-else
									:disabled="ruleForm.serviceState === 1 || ruleForm.serviceState === 2"
									placeholder="存货编码"
									only-key="productCode"
									:title="`存货编码`"
									query-name="productCode"
									:form-data="ruleForm"
									@on-select="onSelectProductCodeChange"
								></remote-search-variety-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="品种">
								<span class="read-only-2">{{ ruleForm.productName }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="棉花年度">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.cottonYear }}</span>
								<el-date-picker
									v-else
									v-model="ruleForm.cottonYear"
									type="year"
									placeholder="选择年"
									size="medium"
									format="yyyy"
									value-format="yyyy"
									style="width: 100%"
								>
								</el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="供货单位">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.supplyName }}</span>
								<remote-search-enterprise-input
									v-else
									:disabled="ruleForm.serviceState === 1 || ruleForm.serviceState === 2"
									placeholder="供货单位"
									only-key="supplyCode"
									query-name="supplyName"
									:form-data="ruleForm"
									@on-select="onSelectEnterpriseChange"
								></remote-search-enterprise-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="承运单位">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.transportName }}</span>
								<remote-search-product-input
									v-else
									:disabled="ruleForm.serviceState === 1 || ruleForm.serviceState === 2"
									placeholder="承运单位"
									only-key="transportCode"
									query-name="transportName"
									:form-data="ruleForm"
									@on-select="onSelectTransportNameChange"
								></remote-search-product-input>
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
			</div>
			<div ref="box2" style="display: flex" class="margin-bottom-4">
				<el-tag type="primary" effect="plain">
					<span class="el-icon-document item-gap"></span>
					<span>原批明细</span>
				</el-tag>
				<jk-button v-if="pageType !== 'detail'" size="mini" style="margin-left: 5px" type="primary" :disabled="ruleForm.serviceState === 1 || ruleForm.serviceState === 2" @click="addProductList">添加明细</jk-button>
			</div>
			<jk-table border :data="ruleForm.itemList" :max-height="dialogTableHeight - 50">
				<vxe-column title="操作" align="left" field="productCode" :width="65">
					<template #header>
						<span slot="reference">操作</span>
					</template>
					<template slot-scope="scope">
						<div slot="reference" class="drag-info-icon" style="color: #2d8cf0;font-size: 13px;">
							<jk-button v-if="pageType !== 'detail'" icon="el-icon-minus" size="mini" :disabled="ruleForm.serviceState === 1 || ruleForm.serviceState === 2" @click="copyProductList(scope.rowIndex)"></jk-button>
						</div>
						<span>{{ scope.row.productCode }}</span>
					</template>
				</vxe-column>
				<vxe-column title="序号" align="left" field="code" :min-width="110">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.code }}</span>
						<el-input v-else v-model="scope.row.code" disabled size="mini" placeholder="序号" />
					</template>
				</vxe-column>
				<vxe-column title="车号" align="left" field="carCode" :min-width="110">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.carCode }}</span>
						<el-input v-else v-model="scope.row.carCode" size="mini" placeholder="车号" />
					</template>
				</vxe-column>
				<vxe-column title="发货日期" align="left" field="belongDate" :min-width="135">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.belongDate }}</span>
						<jk-date-picker
							v-else
							v-model="scope.row.belongDate"
							placeholder="选择日期"
							size="mini"
						/>
					</template>
				</vxe-column>
				<vxe-column title="原批" align="left" field="primaryBatchCode" :min-width="140">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.primaryBatchCode }}</span>
						<el-input v-else v-model="scope.row.primaryBatchCode" size="mini" placeholder="原批" />
					</template>
				</vxe-column>
				<vxe-column title="件数" align="left" field="num" :min-width="70">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.num }}</span>
						<jk-number-input v-else v-model="scope.row.num" size="mini" placeholder="件数" />
					</template>
				</vxe-column>
				<vxe-column title="付款" align="left" field="payment" :min-width="110">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.payment }}</span>
						<el-input v-else v-model="scope.row.payment" size="mini" placeholder="付款" />
					</template>
				</vxe-column>
				<vxe-column title="到站" align="left" field="terminal" :min-width="80">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.terminal }}</span>
						<el-input v-else v-model="scope.row.terminal" size="mini" placeholder="到站" />
					</template>
				</vxe-column>
				<vxe-column title="已分配数量" align="left" field="weighNum" :min-width="70"></vxe-column>
				<vxe-column title="未分配数量" align="left" field="residueNum" :min-width="70"></vxe-column>
				<vxe-column title="备注" align="left" field="remark" :min-width="110">
					<template slot-scope="scope">
						<span v-if="pageType === 'detail'">{{ scope.row.remark }}</span>
						<el-select v-else v-model="scope.row.remark" size="mini" placeholder="请选择">
							<el-option
								v-for="item in options"
								:key="item.id"
								:label="item.name"
								:value="item.name"
							>
							</el-option>
						</el-select>
					</template>
				</vxe-column>
				<vxe-column v-if="pageType !== 'add'" title="操作" align="left" field="productCode" :width="80">
					<template #header>
						<span slot="reference">操作</span>
					</template>
					<template slot-scope="scope">
						<div slot="reference" class="drag-info-icon" style="color: #2d8cf0;font-size: 13px;">
							<jk-button v-if="scope.row.serviceState === 3" size="mini" type="warning" @click="onItemRevocationState(scope.row.id)">取消</jk-button>
							<jk-button v-else size="mini" type="primary" @click="itemState(scope.row.id)">完成</jk-button>
						</div>
					</template>
				</vxe-column>
			</jk-table>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '../../../../mixins/cal-dialog-height';
    import remoteSearchProductInput from './components/remote-search-product-input/index.vue';
    import {
        productionArrivedGoodsCleanCloseItem,
        productionArrivedGoodsCloseItem,
        productionArrivedGoodsCreate,
        productionArrivedGoodsGet,
        productionArrivedGoodsUpdate
    } from '@/api/production/arrivedGoodsOrder';
    import remoteSearchEnterpriseInput
        from '/src/views/putInWarehouse/rawCotton/weighingOrder/components/remote-search-enterprise-input/index.vue';
    import remoteSearchVarietyInput
        from '/src/views/putInWarehouse/rawCotton/weighingOrder/components/remote-search-variety-input/index.vue';
    export default {
        mixins: [calHeight],
        components: { remoteSearchEnterpriseInput, remoteSearchProductInput, remoteSearchVarietyInput },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            copy: {
                type: Boolean,
                default: false
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                processList: [],
                cottonYearTime: '',
                tableLoading: false,
                saveBtnLoading: false,
                workshopList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                options: [
                    { id: 0, name: '机采棉' },
                    { id: 1, name: '地产棉' },
                    { id: 2, name: '仓单棉' }
                ],
                ruleForm: {
                    'auditState': 0,
                    'code': '',
                    'contract': '',
                    'cottonYear': '',
                    'itemList': [
                        {
                            'belongDate': '',
                            'carCode': '',
                            'code': '',
                            'num': 1,
                            'payment': '',
                            'primaryBatchCode': '',
                            'primaryBatchId': 0,
                            'remark': '',
                            'terminal': '',
                            'weighNum': 0
                        }
                    ],
                    'productCode': '',
                    'productId': 0,
                    'productName': '',
                    'remark': '',
                    'supplyCode': '',
                    'supplyId': 0,
                    'supplyName': '',
                    'transportCode': '',
                    'transportId': 0,
                    'transportName': '',
                    'unitCode': '',
                    'unitId': 0,
                    'unitName': ''
                },
                rules: {
                    minValue: [{ required: true, trigger: 'change' }],
                    maxValue: [{ required: true, trigger: 'change' }],
                    belongDate: [{ required: true, trigger: 'change' }],
                    tenPrice: [{ required: true, trigger: 'change' }]
                },
                defaultRowData: {
                    'processId': '',
                    'processCode': '',
                    'processName': '',
                    'unitPrice': 0,
                    batchList: []
                }
            };
        },
        methods: {
            onItemRevocationState(id) {
                this.$confirm('此操作将撤销该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    return productionArrivedGoodsCleanCloseItem({ id: id }).then(res => {
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.getDetailRequest();
                            this.$message({
                                type: 'success',
                                message: '撤销成功!'
                            });
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            itemState(id) {
                this.$confirm('此操作将完成该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const api = productionArrivedGoodsCloseItem;
                    api({ id: id }).then(res => {
                        this.saveBtnLoading = false;
                        if (res.data.status === 200) {
                            this.getDetailRequest();
                            this.$message({
                                type: 'success',
                                message: '已完成!'
                            });
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            addProductList() {
                this.ruleForm.itemList.push(
                    {
                        'belongDate': '',
                        'carCode': '',
                        'code': '',
                        'num': 1,
                        'payment': '',
                        'primaryBatchCode': '',
                        'primaryBatchId': 0,
                        'remark': '',
                        'terminal': '',
                        'weighNum': 0
                    }
                );
                this.ruleForm.itemList.forEach((x) => {
                    x.terminal = '常德';
                });
            },
            copyProductList(index) {
                this.ruleForm.itemList.splice(index, 1);
            },
            onSelectProductCodeChange(e) {
                this.ruleForm.productCode = e.code;
                this.ruleForm.productName = e.name;
                this.ruleForm.productId = e.id;
            },
            onSelectTransportNameChange(e) {
                this.ruleForm.transportCode = e.code;
                this.ruleForm.transportName = e.name;
                this.ruleForm.transportId = e.id;
            },
            onSelectEnterpriseChange(e) {
                this.ruleForm.supplyCode = e.code;
                this.ruleForm.supplyName = e.name;
                this.ruleForm.supplyId = e.id;
            },
            onChildAddBtn(rowIndex, batchIndex) {
                if (batchIndex || batchIndex === 0) {
                    this.ruleForm.configItem[rowIndex].batchList.splice(batchIndex + 1, 0, {});
                } else {
                    this.ruleForm.configItem[rowIndex].batchList.push({});
                }
            },
            onDeleteBtn(scope) {
                this.ruleForm.configItem.splice(scope.rowIndex, 1);
            },
            onAddBtn() {
                this.ruleForm.configItem.push(JSON.parse(JSON.stringify(this.defaultRowData)));
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId && this.copy) {
                    params.auditState = 1;
                    delete params.id;
                }
                return params;
            },
            onConfirmBtn() {
                const allNamesEmpty = this.ruleForm.itemList.every(obj =>
                    obj.primaryBatchCode !== ''
                );
                this.$refs['ruleForm'].validate(valid => {
                    // if (valid && allNamesEmpty) {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                const api = !this.dataId || this.copy ? productionArrivedGoodsCreate : productionArrivedGoodsUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return productionArrivedGoodsGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.configItem = resData.configItem || [];
                        this.ruleForm = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                if (!this.ruleForm.itemList[0].terminal) {
                    this.$set(this.ruleForm.itemList[0], 'terminal', '常德');
                }
                this.processList = this.$store.state.user.userProcess.processList || [];
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.$nextTick(() => {
                        this.$refs.ruleForm.clearValidate();
                    });
                    this.getDependentData();
                }
            }
        }
    };
</script>
